<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="开放时段" prop="openTime">
        <el-time-picker
          is-range
          v-model="form.openTime"
          value-format="HH:mm:ss"
          format="HH:mm"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间">
        </el-time-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['campus:room:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['campus:room:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['campus:room:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['campus:room:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="图片" align="center" prop="imageUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="可容纳总人数" align="center" prop="capacity" />
      <el-table-column label="当前人数" align="center" prop="currentPeople" />
      <el-table-column label="开放时段" align="center" prop="openTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ statusFormat(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleReserve(scope.row)"
          >预约</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:room:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['campus:room:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自习室信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="可容纳总人数" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入可容纳总人数" />
        </el-form-item>
        <el-form-item label="开放时段" prop="openTime">
          <el-time-picker
            is-range
            v-model="form.openTime"
            value-format="HH:mm"
            format="HH:mm"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="闭门中" value="0"></el-option>
            <el-option label="开放中" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 预约对话框 -->
    <el-dialog title="预约座位" :visible.sync="reserveOpen" width="1000px" append-to-body>
      <el-form ref="reserveForm" :model="reserveForm" label-width="80px">
        <el-form-item label="自习室">
          <el-input v-model="reserveForm.roomName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="座位选择">
          <el-card v-for="seat in seatList" :key="seat.id" :class="{'selected-seat': selectedSeat && selectedSeat.id === seat.id}" style="display: inline-block; width: 80px; margin: 5px;" :body-style="{ padding: '10px' }">
            <div style="text-align: center;">
              <el-button 
                :type="getSeatButtonType(seat.status)" 
              :disabled="seat.status !==0" 
                @click="selectSeat(seat)"
                circle
                style="width: 35px; height: 30px; font-size: 12px; padding: 0;">
                {{ seat.number }}
              </el-button>
              <div style="font-size: 12px; margin-top: 5px;">
                <span>{{ getSeatStatusText(seat.status) }}</span>
                <i :class="getSeatStatusIcon(seat.status)" :style="{ color: getSeatStatusColor(seat.status), marginLeft: '3px' }"></i>
              </div>
            </div>
          </el-card>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReserve" :disabled="!selectedSeat">确 定</el-button>
        <el-button @click="cancelReserve">取 消</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom, getRoomDetailWithSeats } from "@/api/campus/room"
import { reserveSeat } from "@/api/campus/seat"

export default {
  name: "Room",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自习室信息表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        openTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "图片不能为空", trigger: "blur" }
        ],
        capacity: [
          { required: true, message: "可容纳总人数不能为空", trigger: "blur" }
        ],
        openTime: [
          { required: true, message: "开放时段不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态：0-闭门中，1-开放中不能为空", trigger: "change" }
        ],
      },
      // 预约对话框
      reserveOpen: false,
      reserveForm: {
        roomId: null,
        roomName: null,
        seatId: null
      },
      seatList: [],
      selectedSeat: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询自习室信息列表 */
    getList() {
      this.loading = true
      listRoom(this.queryParams).then(response => {
        this.roomList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        imageUrl: null,
        capacity: null,
        currentPeople: null,
        openTime: null,
        status: null,
        reservedPeople: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加自习室信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRoom(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改自习室信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建一个表单副本用于提交
          const submitForm = { ...this.form };
          
          // 如果开放时段是数组格式，则转换为字符串
          if (Array.isArray(submitForm.openTime)) {
            submitForm.openTime = submitForm.openTime.join("至");
          }
          
          if (this.form.id != null) {
            updateRoom(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRoom(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除自习室信息编号为"' + ids + '"的数据项？').then(function() {
        return delRoom(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('campus/room/export', {
        ...this.queryParams
      }, `room_${new Date().getTime()}.xlsx`)
    },
    /** 状态格式化 */
    statusFormat(row) {
      const statusMap = {
        '0': '闭门中',
        '1': '开放中'
      };
      return statusMap[row.status] || row.status;
    },
    // 预约按钮操作
    handleReserve(row) {
      this.reserveForm.roomId = row.id
      this.reserveForm.roomName = row.name
      this.selectedSeat = null
      this.getRoomDetailWithSeats(row.id)
      this.reserveOpen = true
    },
    // 获取自习室详情及座位列表
    getRoomDetailWithSeats(roomId) {
      getRoomDetailWithSeats(roomId).then(response => {
        this.seatList = response.data || []
      })
    },
    // 获取座位按钮类型
    getSeatButtonType(status) {
      const statusMap = {
        '0': 'success',  // 空闲 - 绿色
        '1': 'danger'    // 有人 - 红色
      }
      return statusMap[status] || 'info'
    },
    // 获取座位状态文本
    getSeatStatusText(status) {
      const statusMap = {
        '0': '空闲',
        '1': '有人'
      }
      return statusMap[status] || '未知'
    },
    // 获取座位状态图标
    getSeatStatusIcon(status) {
      return 'el-icon-circle-check'
    },
    // 获取座位状态颜色
    getSeatStatusColor(status) {
      const colorMap = {
        '0': '#67C23A',  // 绿色
        '1': '#F56C6C'   // 红色
      }
      return colorMap[status] || '#909399'
    },
    // 选择座位
    selectSeat(seat) {
      // 如果点击的是已经选中的座位，则取消选中
      if (this.selectedSeat && this.selectedSeat.id === seat.id) {
        this.selectedSeat = null
        this.reserveForm.seatId = null
      } else {
        // 否则选中该座位
        this.selectedSeat = seat
        this.reserveForm.seatId = seat.id
      }
    },
    // 提交预约
    submitReserve() {
      // 调用预约接口
      reserveSeat(this.reserveForm.seatId).then(response => {
        this.$modal.msgSuccess("预约成功，座位号：" + this.selectedSeat.number)
        this.reserveOpen = false
      }).catch(error => {
        this.$modal.msgError("预约失败：" + error.message)
      })
    },
    // 取消预约
    cancelReserve() {
      this.reserveOpen = false
      this.selectedSeat = null
      this.reserveForm = {
        roomId: null,
        roomName: null,
        seatId: null
      }
    }
  }
}
</script>

<style scoped>
.selected-seat {
  border: 2px solid #409EFF !important;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}
</style>
